package com.zhaoyue.study.concurrency.pools;

import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 2017/3/8
 * Time: 10:56
 * To change this template use File | Settings | File Templates.
 */
public class PoolDemo {

    static class Thread1 implements Runnable{
        @Override
        public void run() {
            System.out.println("名称：" + Thread.currentThread().getName());
        }
    }

    static class Thread2 implements Callable<String>{
        @Override
        public String call() throws Exception {
            return "2";
        }
    }

    public static void main(String[] args) throws Exception {

//        Executor executor = Executors.newFixedThreadPool(2);
//        for (int i = 0; i < 10; i++) {
//            executor.execute(new Thread1());
//        }

        ExecutorService service =  new ThreadPoolExecutor(2,4,60,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
        try{
            for (int i = 0; i < 10; i++) {
                Future<String> future = service.submit(new Thread2());
                System.out.println(future.get());
                System.out.println("------------------");
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }

        service.shutdown();

        System.out.println("-------------");
        service =  new ThreadPoolExecutor(2,4,60,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
        ExecutorCompletionService<String> completionService = new ExecutorCompletionService<String>(service);
        for (int i = 0; i < 10; i++) {
            completionService.submit(new Thread2());
        }

        int size = 0;
        while (size < 10){
            Future<String> future =  completionService.take();
            System.out.println(future.get());
            size ++;
        }
        service.shutdown();

        System.getProperty("","");






    }



}
